import { Application } from 'egg'

const addEvent = async (app: Application, path: string) => {
  const nsp = app.io.of(path)
  nsp.on('connect', socket => {
    socket.on('disconnect', reason => {
      app.logger.info('on disconnect', reason)
    })
    socket.on('error', error => {
      app.logger.info('on error', error)
    })
    socket.on('disconnecting', reason => {
      app.logger.info('on disconnecting', reason)
    })

    // nsp.emit(socket.id, `hello '${socket.id}' ${socket.nsp.name}`)

    // socket.handshake
    app.logger.info('on connect',
      nsp.name, socket.id, socket.connected, socket.rooms,
      socket.eventNames(), JSON.stringify(Object.keys(socket.handshake)))
  })
  return nsp
}

export default async (app: Application) => {
  const rootNsp = await addEvent(app, '/')
  // await addEvent(app, '/message')

  rootNsp.on('ping', socket => {
    app.logger.info('on ping')
  })
  rootNsp.emit('ping', `${app.config.name} socket online!`)
}
